package com.robot.common.handler;


import com.robot.common.exception.BusinessException;
import com.robot.common.result.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;

@RestControllerAdvice
public class GlobalDefaultExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);



    /**
     * 处理异常-BusinessException
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Response<?> businessExceptionHandler(BusinessException e){
        log.error("businessException:" + e.getMessage(),e);
        return Response.error(e.getErrorCode(),e.getErrorMessage());
    }


    /**
     * NoHandlerFoundException 404 异常处理
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response handlerNoHandlerFoundException(NoHandlerFoundException exception) {
        outPutErrorWarn(NoHandlerFoundException.class, HttpStatus.NOT_FOUND, exception);
        return Response.error(HttpStatus.NOT_FOUND.value(), exception.getMessage());
    }

    /**
     * 通用异常处理
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Response exceptionHandler(HttpServletRequest httpServletRequest, Exception e) {
        return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }


    public void outPutError(Class errorType, Enum secondaryErrorType, Throwable throwable) {
        log.error("[{}] {}: {}", errorType.getSimpleName(), secondaryErrorType, throwable.getMessage(), throwable);
    }

    public void outPutErrorWarn(Class errorType, Enum secondaryErrorType, Throwable throwable) {
        log.warn("[{}] {}: {}", errorType.getSimpleName(), secondaryErrorType, throwable.getMessage());
    }
}
